package com.bridgeintelligent.tag.customer.looklike;

import com.bridgeintelligent.tag.constants.bulkload.IssueMqMsg;
import com.bridgeintelligent.tag.constants.bulkload.MQConfig;
import com.bridgeintelligent.tag.customer.entity.IssueLog;
import com.bridgeintelligent.tag.customer.mapper.*;
import com.bridgeintelligent.tag.user.mgmt.pojo.User;
import com.bridgeintelligent.tag.utils.DateHelper;
import com.bridgeintelligent.tag.webserver.security.TagSecurityHelper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.wayneleo.quickstart.framework.IDGenerator;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.Objects;

@Service
@Transactional(rollbackFor = Exception.class)
@AllArgsConstructor
@Slf4j
public class LookLikeIssueServiceImpl implements ILookLikeIssueService {

    private static final String EFFECTIVE = "01";

    private static final String PASS = "4";

    protected RocketMQTemplate rocketMQTemplate;

    private LookLikeExportMapper lookLikeExportMapper;

    private LookLikeIssueMapper lookLikeIssueMapper;

    private ObjectMapper objectMapper;

    private IssueLogMapper issueLogMapper;

    private IssueTaskMapper issueTaskMapper;

    private ILookLikeService lookLikeService;

    @Override
    public void addLookLikeIssue(LookLikeIssue issue) {

        User user = TagSecurityHelper.currentUser();
        //保存导出配置信息
        LookLikeExportConfig config = issue.getConfig();
        config.setId(IDGenerator.gen()).setDateTime(DateHelper.currentDateTime(DateHelper.PATTERN_DATE_1));
        lookLikeExportMapper.addLookExportConfig(config);

        //保存Issue表信息
        issue.setId(IDGenerator.gen())
                .setLookConfigId(config.getId())
                .setApproveStatus(PASS)
                .setState(EFFECTIVE)
                .setIsDel("00")
                .setCreatorId(user.getUserId())
                .setCreateTime(new Date())
                .setUpdateTime(new Date());
        lookLikeIssueMapper.addLookIssue(issue);

        //保存IssueTask表信息
        lookLikeIssueMapper.addLookIssueTask(issue);

        //保存IssueTaskLog表信息
        LookLikeIssueTaskLog issueTaskLog = new LookLikeIssueTaskLog();
        BeanUtils.copyProperties(issue, issueTaskLog);
        issueTaskLog.setIssueId(issue.getId());
        issueTaskLog.setId(IDGenerator.gen());
        lookLikeIssueMapper.addLookIssueTaskLog(issueTaskLog);

        //保存IssueLog表信息
        IssueLog issueLog = new IssueLog();
        issueLogMapper.addLog(issueLog.setId(issueTaskLog.getId())
                .setUpdateTime(new Date()).setCreateTime(new Date()).setDataDate(DateHelper.currentDateTime(DateHelper.PATTERN_DATE_8))
                .setState("0").setIsRetry("1"));

        //发送MQ消息
        try {
            IssueMqMsg issueMqMsg = new IssueMqMsg();
            issueMqMsg.setId(issueLog.getId());
            issueMqMsg.setIndexId(config.getEsIndex());
            String msg = objectMapper.writeValueAsString(issueMqMsg);
            rocketMQTemplate.convertAndSend(MQConfig.FILE_ISSUE_TOPIC, msg);
            issueLogMapper.updateLog(new IssueLog().setId(issueLog.getId()).setState("1").setUpdateTime(new Date()));
            log.info("相似客群立即下发发送mq成功：{}",issueLog.getId());
        } catch (Exception e) {
            log.error("相似客群立即下发任务失败:"+issueLog.getId(), e);
            issueLogMapper.updateLog(new IssueLog().setId(issueLog.getId()).setState("3").setUpdateTime(new Date()).setReason("发送MQ消息失败"));
        }

        lookLikeService.addOperation(OperationEnum.EXPORT.getCode(),issue.getCustomersId());
    }

    @Override
    public void updateLookLikeIssue(LookLikeIssue issue) {
        User user = TagSecurityHelper.currentUser();
        //修改Issue表信息
        issue.setApproveStatus(PASS)
                .setState(EFFECTIVE)
                .setIsDel("00")
                .setCreatorId(user.getUserId())
                .setUpdateTime(new Date());
        lookLikeIssueMapper.updateLookIssue(issue);
        //修改IssueTask表信息
        lookLikeIssueMapper.updateLookIssueTask(issue);

        //保存IssueTaskLog表信息
        LookLikeIssueTaskLog issueTaskLog = new LookLikeIssueTaskLog();
        BeanUtils.copyProperties(issue, issueTaskLog);
        issueTaskLog.setIssueId(issue.getId());
        issueTaskLog.setId(IDGenerator.gen());
        lookLikeIssueMapper.addLookIssueTaskLog(issueTaskLog);

        //保存IssueLog表信息
        IssueLog issueLog = new IssueLog();
        issueLogMapper.addLog(issueLog.setId(issueTaskLog.getId())
                .setUpdateTime(new Date()).setCreateTime(new Date()).setDataDate(DateHelper.currentDateTime(DateHelper.PATTERN_DATE_8))
                .setState("0").setIsRetry("1"));

        //发送MQ消息
        try {
            IssueMqMsg issueMqMsg = new IssueMqMsg();
            issueMqMsg.setId(issueLog.getId());
            issueMqMsg.setIndexId(issue.getConfig().getEsIndex());
            String msg = objectMapper.writeValueAsString(issueMqMsg);
            rocketMQTemplate.convertAndSend(MQConfig.FILE_ISSUE_TOPIC, msg);
            issueLogMapper.updateLog(new IssueLog().setId(issueLog.getId()).setState("1").setUpdateTime(new Date()));
            log.info("相似客群立即下发发送mq成功：{}",issueLog.getId());
        } catch (Exception e) {
            log.error("相似客群立即下发任务失败:"+issueLog.getId(), e);
            issueLogMapper.updateLog(new IssueLog().setId(issueLog.getId()).setState("3").setUpdateTime(new Date()).setReason("发送MQ消息失败"));
        }

        lookLikeService.addOperation(OperationEnum.EXPORT.getCode(),issue.getCustomersId());
    }

    @Override
    public void updateLookLikeIssueTask(LookLikeIssue issue) {
        User user = TagSecurityHelper.currentUser();
        issue.setApproveStatus(PASS)
                .setState(EFFECTIVE)
                .setIsDel("00")
                .setCreatorId(user.getUserId())
                .setUpdateTime(new Date());
        //修改IssueTask表信息
        lookLikeIssueMapper.updateLookIssueTask(issue);
    }

    @Override
    public boolean isRun(String taskId) {
        //立即下发校验是否有正在执行的任务0待运行、1正在运行(2成功3失败的状态不管)
        Integer count = issueTaskMapper.immediateCheckCount(taskId);
        if(count>0){
            return true;
        }
        return false;
    }


    @Override
    public boolean checkName(String id , String issueName) {
        String dbId = lookLikeIssueMapper.checkIssueName(issueName);
        if (StringUtils.isEmpty(dbId)){
            return false;
        }else{
            if (!StringUtils.isEmpty(id) && StringUtils.equals(id,dbId)){
                return false;
            }
        }
        return true;
    }

    @Override
    public LookLikeIssue findLookIssue(String id) {
        //先查询Issue基础信息
        LookLikeIssue lookIssue = lookLikeIssueMapper.findLookIssue(id);
        if (lookIssue != null && !StringUtils.isEmpty(lookIssue.getLookConfigId())){
            LookLikeExportConfig lookExportConfig = lookLikeExportMapper.findLookExportConfig(lookIssue.getLookConfigId());
            if (lookExportConfig != null){
                lookIssue.setConfig(lookExportConfig);
            }
        }
        return lookIssue;
    }

    @Override
    public LookLikeIssue findLookIssueTask(String id) {
        LookLikeIssue lookIssueTask = lookLikeIssueMapper.findLookIssueTask(id);
        if (lookIssueTask != null && !StringUtils.isEmpty(lookIssueTask.getLookConfigId())){
            LookLikeExportConfig lookExportConfig = lookLikeExportMapper.findLookExportConfig(lookIssueTask.getLookConfigId());
            if (lookExportConfig != null){
                lookIssueTask.setConfig(lookExportConfig);
            }
        }
        return lookIssueTask;
    }

    @Override
    public void istry(String logId) {
        User user = TagSecurityHelper.currentUser();
        //先根据logId查询IssueTaskLog信息
        String esIndex = "";
        LookLikeIssueTaskLog lookIssueTaskLog = Objects.requireNonNull(lookLikeIssueMapper.findLookIssueTaskLog(logId));
        if (!StringUtils.isEmpty(lookIssueTaskLog.getLookConfigId())){
            LookLikeExportConfig config = lookLikeExportMapper.findLookExportConfig(lookIssueTaskLog.getLookConfigId());
            if (config != null ){
                esIndex = config.getEsIndex();
            }
        }

        lookIssueTaskLog.setId(IDGenerator.gen())
                .setCreateTime(new Date())
                .setUpdateTime(new Date())
                .setCreatorId(Objects.requireNonNull(user).getUserId())
                .setIsDel("00");
        lookLikeIssueMapper.addLookIssueTaskLog(lookIssueTaskLog);

        //保存IssueLogInfo表信息
        IssueLog issueLog = new IssueLog();
        issueLogMapper.addLog(issueLog.setId(lookIssueTaskLog.getId())
                .setUpdateTime(new Date()).setCreateTime(new Date()).setDataDate(DateHelper.currentDateTime(DateHelper.PATTERN_DATE_8))
                .setState("0").setIsRetry("1"));

        //发送MQ消息
        try {
            IssueMqMsg issueMqMsg = new IssueMqMsg();
            issueMqMsg.setId(issueLog.getId());
            issueMqMsg.setIndexId(esIndex);
            String msg = objectMapper.writeValueAsString(issueMqMsg);
            rocketMQTemplate.convertAndSend(MQConfig.FILE_ISSUE_TOPIC, msg);
            issueLogMapper.updateLog(new IssueLog().setId(issueLog.getId()).setState("1").setUpdateTime(new Date()));
            log.info("相似客群立即下发重试操作发送mq成功：{}",issueLog.getId());
        } catch (Exception e) {
            log.error("相似客群立即下发任务重试操作失败:"+issueLog.getId(), e);
            issueLogMapper.updateLog(new IssueLog().setId(issueLog.getId()).setState("3").setUpdateTime(new Date()).setReason("发送MQ消息失败"));

        }
        lookLikeService.addOperation(OperationEnum.EXPORT.getCode(),lookIssueTaskLog.getCustomersId());

    }


}
